package top.idcard.agent.biz.rw.write.local;

import top.idcard.agent.biz.entity.Certification;
import top.idcard.agent.biz.rw.write.AbstractWrite;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wx
 * @version 1.0
 * @date 2021/1/31 3:01 下午
 */
public class LocalCertificationFileWrite extends AbstractWrite<Certification> {

    protected String fileParentPath;
    protected FileOutputStream fileOutputStream;

    @Override
    public void init() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String today = simpleDateFormat.format(new Date());
        fileParentPath = "prePath" + File.separator + today;
        File file = new File(fileParentPath);
        createDirectory(file);
        String filePath = fileParentPath + File.separator + today;
        try {
            fileOutputStream = new FileOutputStream(filePath, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void createDirectory(File path){
        if(path != null) {
            if (path.exists()) {
                if (!path.isDirectory()) {
                    createDirectory(path.getParentFile());
                    path.mkdir();
                }
            } else {
                createDirectory(path.getParentFile());
                path.mkdir();
            }
        }
    }

    public void writeObject(Certification data){
        write(translateBytes(data));
    }

    public void write(byte[] data){
        try {
            fileOutputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close(){
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String dataFrom() {
        return "device_local";
    }

    @Override
    public byte[] translateBytes(Certification certification) {
        if(certification == null){
            return new byte[0];
        }
        return certification.getBytes();
    }
}
